<?php

/**************************************************************************************************************************
 *                                                      === XERO ===                                                      *
 *                                                  hello.xero@gmail.com                                                  *
 * We provide a FREE software consultancy and development service to ensure that your ideas will be realized.             *
 * Gurus in C++ / C / (ARM, Z80, Intel, 68K) Assembler / LISP / LUA / Smalltalk / PHP / Java / Symbian / Windows /        *
 * Linux / Kernels / Architecture / API design / Penetration / Protection / Graphics / Audio                              *
 **************************************************************************************************************************/


/**
 * Utility functions
 * @author XERO
 */


/**
 * Recursively merge an array. Values in $aArray2 override values in $aArray1 with the same key.
 *
 * @param array $aArray1
 * @param array $aArray2
 * @return array
 */
function multiMerge(array $aArray1, array $aArray2)
{
    foreach ($aArray2 as $key => $value) {
        $aArray1[$key] = (is_array($value) && !empty($value)) ? multiMerge($aArray1[$key], $value) : $value;
    }
    return $aArray1;
}


/**
 * Hash a flat table like array to create a nested hierarchical array.
 *
 * @param array $aTable Flat array queried from database
 * @param mixed $aFields Array of fields to create the hash with.
 *                       If ':index' is specified then a numeric array index is created.
 * @param mixed $aKeepFields The fields to keep. All fields are kept when this argument is not specified.
 * @return array
 */
function hashByFields(array &$aTable, $aFields, $aKeepFields = null)
{
    // Create an array of keys with field names.
    settype($aFields, 'array');

    $hashKeys = array_fill_keys($aFields, null);
    $keepKeys = array_fill_keys((array)$aKeepFields, null);
    $hash = array();

    foreach ($aTable as $record) {
        settype($record, 'array');

        $item = &$hash;
        foreach ($aFields as $field) {
            if ($field == ':index') {
                // Numeric array index.
                $item = &$item[];
            } else {
                if (!array_key_exists($field, $record)) {
                    throw new Exception("Field '{$field}' does not appear in the record.");
                }
                $item = &$item[$record[$field]];
            }
        }

        // Use all the remaining fields in the record that are not already used in the hash.
        $record = array_diff_key($record, $hashKeys);
        if (!empty($keepKeys)) {
            $record = array_intersect_key($record, $keepKeys);
        }

        // Don't need the whole array if it only contains 1 element.
        // This ensures the output is compatible with form helpers.
        $item = (count($record) == 1 ? reset($record) : $record);
    }

    return $hash;
}


/**
 * Get a string representation of an XML attribute array.
 *
 * @param array $aAttrs
 * @return string
 */
function toAttributeString(array $aAttrs)
{
    $output = array();
    foreach ($aAttrs as $key => $attr) {
        // Convert array to string containing values seperated by spaces.
        if (is_array($attr)) {
            $attr = implode(' ', $attr);
        }

        if (!empty($attr)) {
            $output[] = "{$key} = \"{$attr}\"";
        }
    }
    return implode(' ', $output);
}


/**
 * Initialize the database object.
 * Remember to enable PDO in the PHP installation.
 *
 * @return unknown
 */
function initDb()
{
    define('DB_NAME', 'lingoblog');
    $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);

    // Make sure the MySQL database returns the data as UTF8.
    // Witout this it will return rubbish!
    $db->exec("SET NAMES 'utf8';");

    return $db;
}


/**
 * Escape a string.
 *
 * @param string $aStr String to escape.
 * @param string $aCharset The character set. Defaults to UTF-8.
 * @return string.
 */
function escape($aStr, $aCharset = 'UTF-8')
{
    return htmlspecialchars($aStr, ENT_COMPAT, $aCharset);
}
